package com.gewe.wxChat.utils;

import com.alibaba.fastjson2.JSONObject;
import com.gewe.wxChat.model.enums.OrderYaoYueStatusEnum;
import okhttp3.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

public class SanZhiUtils {
    private static OkHttpClient client = new OkHttpClient();
    
    private final static Logger logger= LoggerFactory.getLogger(SanZhiUtils.class);
    
    private static String LLK_TOKEN;
    
    public static String getHeTong(String frtId){
        String requestBody = "{\"frtId\":\"" + frtId + "\"}";

        Request request = new Request.Builder()
                .url("https://www.lingluke.cn/api/frt/order/getTransContractUrl")
                .post(RequestBody.create(MediaType.parse("application/json"), requestBody))
                .header("Accept", "application/json")
                .header("Accept-Language", "zh-CN,zh;q=0.9")
                .header("Authorization", "Bearer "+LLK_TOKEN)
                .header("Cache-Control", "no-cache")
                .header("Connection", "keep-alive")
                .header("Content-Type", "application/json")
                .header("Origin", "https://www.lingluke.cn")
                .header("Pragma", "no-cache")
                .header("Referer", "https://www.lingluke.cn/whPlatForm/whplatformorderclientlist")
                .header("Sec-Fetch-Dest", "empty")
                .header("Sec-Fetch-Mode", "cors")
                .header("Sec-Fetch-Site", "same-origin")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36")
                .header("apiversion", "1.5.0.1")
                .header("sec-ch-ua", "\"Google Chrome\";v=\"129\", \"Not=A?Brand\";v=\"8\", \"Chromium\";v=\"129\"")
                .header("sec-ch-ua-mobile", "?0")
                .header("sec-ch-ua-platform", "\"Windows\"")
                .build();

        try (Response response = client.newCall(request).execute()) {
            String result = response.body().string();

            JSONObject jsonObject = JSONObject.parseObject(result);
            HashMap<String, Object> data = (HashMap<String, Object>) jsonObject.get("data");
            String msg = data.get("msg").toString();
            String signUrl=data.get("signUrl").toString();
            if(StringUtils.isNotBlank(msg) && msg.contains("当前运单电子运输合同状态不是")){
                return "合同签了";
            }else if(StringUtils.isNotBlank(signUrl)){
                return "  e签宝合同:"+signUrl;
            }else if(StringUtils.isBlank(msg) && StringUtils.isBlank(signUrl)){
                return "  e签宝正在创建中，5分钟后重发";
            }
        } catch (IOException e) {
            
            logger.error("合同请求失败", e);
            return "";
        }
        return "";
    }
    
    //网货平台的邀约
    public static HashMap<String,Object> wangHuoYaoyue(String formId){
        HashMap<String, Object> map=new HashMap<>();
        String requestBody = "{\"outTradeNo\":\"" + formId + "\",\"whSourceType\":0}";


        Request request = new Request.Builder()
                .url("https://www.lingluke.cn/api/frt/web/order/getFrtOrderPlatFormOrderClientByPageList?pageNo=1&pageSize=20&current=1")
                .post(RequestBody.create(MediaType.parse("application/json"), requestBody)) // 需要指定媒体类型和请求体
                .header("Accept", "application/json")
                .header("Accept-Language", "zh-CN,zh;q=0.9")
                .header("Authorization", "Bearer "+LLK_TOKEN)
                .header("Cache-Control", "no-cache")
                .header("Connection", "keep-alive")
                .header("Content-Type", "application/json")
                .header("Origin", "https://www.lingluke.cn")
                .header("Pragma", "no-cache")
                .header("Referer", "https://www.lingluke.cn/whPlatForm/whplatformorderclientlist")
                .header("Sec-Fetch-Dest", "empty")
                .header("Sec-Fetch-Mode", "cors")
                .header("Sec-Fetch-Site", "same-origin")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36")
                .header("apiversion", "1.5.0.1")
                .header("sec-ch-ua", "\"Chromium\";v=\"130\", \"Google Chrome\";v=\"130\", \"Not?A_Brand\";v=\"99\"")
                .header("sec-ch-ua-mobile", "?0")
                .header("sec-ch-ua-platform", "\"Windows\"")
                .build();

        try (Response response = client.newCall(request).execute()) {
            //根据结果判断是不是网货的单
            String result = response.body().string();

            JSONObject jsonObject = JSONObject.parseObject(result);
            HashMap<String, Object> data = (HashMap<String, Object>) jsonObject.get("data");
            List<Object> rows = (List<Object>) data.get("rows");
            
            //判断是否是网货
            if (CollectionUtils.isEmpty(rows) || rows.size() == 0) {
                map.put("isWangHuo",false);
                return map;
            }
            JSONObject frtOrder = (JSONObject) rows.get(0);
            //获取网货编码
            map.put("whSourceType",frtOrder.get("whSourceType"));
            map.put("isWangHuo",true);

            
            if((Integer) frtOrder.get("whSourceType") != 160){
                map.put("yaoyue","非宝奇运单，无法通过短信邀约");
            }
            String frtId = frtOrder.getString("id");
            //邀约状态
            Integer yaoYueStatus= Integer.valueOf(frtOrder.getString("yaoYue"));
            //下一步
            String stepRemark=frtOrder.getString("stepRemark");
            //司机名字
            String carrierName=frtOrder.getString("carrierName");
            //运单号
            String billFormId=frtOrder.getString("formId");
            
            //如果是邀约中状态，则展示邀约地址
            if((Integer) frtOrder.get("whSourceType") == 160 && (stepRemark.equals("司机签署注册协议中,请联系司机") 
                    || stepRemark.equals("司机未在邀约协议中进行人脸识别，请联系司机") )){
                String yaoYue = "https://www.lingluke.cn/wanghuo/baoQi/signing?frtId=" + frtId + "&flag=0";
                map.put("yaoyue",yaoYue);
            }else if ((Integer) frtOrder.get("whSourceType") == 160){
                map.put("yaoyue",OrderYaoYueStatusEnum.getDesc(yaoYueStatus));
            }
            
            String temp="";
            if(StringUtils.isBlank(stepRemark) && (Integer) frtOrder.get("whSourceType") == 160){
                temp=("邀约链接正在创建中，5分钟后重发");
            }else if(stepRemark.equals("车队长签署注册协议中,请联系车队长")){
                temp=("   【车队长邀约地址】："+"https://www.lingluke.cn/wanghuo/baoQi/signing?frtId=" + frtId + "&flag=1");
            }else if(stepRemark.equals("创建实时运单成功")){
                temp=("运单创建好了");
            } else if(stepRemark.equals("司机签署代收协议中，请联系司机在宝奇小程序或者领路客短信上进行签署")){
                temp=("运单创建好了,请提醒司机签署代收协议");
            } else if(stepRemark.equals("实时单认证中")){
                temp="实时单认证中,等下就好了";
            } else if (stepRemark.equals("宝奇新增司机成功") || stepRemark.equals("宝奇新增车辆成功") ||stepRemark.equals("宝奇维护收款人银行卡成功")) {
                temp=("已经签署邀约，处于"+stepRemark +"阶段");
            } else if (stepRemark.equals("宝奇司机签署注册协议成功")) {
                temp=("司机签署注册协议成功");
            } else if(stepRemark.contains("异常") || stepRemark.contains("失败")){
                if(stepRemark.contains("重复提交")){
                    temp=("资料认证有问题，去资料认证界面重新提交下，就可以解决");
                }else {
                    temp=(stepRemark);
                }
            }else {
                temp=stepRemark;
            }
            map.put("billFormId",billFormId);
            map.put("carrierName",carrierName);
            map.put("frtId",frtId);
            map.put("stepRemark",temp);
            return map;
        }catch (Exception e){
            logger.info("查询网货邀约异常"+e);
        }
        return null;
    }


    //去运单管理中查询运单，这里包含网货运单和非网货运单
    public static HashMap<String,Object> yunDanList(String formId){
        HashMap<String, Object> map=new HashMap<>();
        StringBuilder  stringBuilder=new StringBuilder();
        String requestBody = "{\"outTradeNos\":[\""+formId+"\"],\"listType\":0,\"tsStatusList\":[],\"isZdDispatcher\":2,\"isWf\":0}";

        Request request = new Request.Builder()
                .url("https://www.lingluke.cn/api/frt/order/getFrtOrderByListPage?pageNo=1&pageSize=20&current=1")
                .post(RequestBody.create(MediaType.parse("application/json"), requestBody)) // 需要指定媒体类型和请求体
                .header("Accept", "application/json")
                .header("Accept-Language", "zh-CN,zh;q=0.9")
                .header("Authorization", "Bearer "+LLK_TOKEN)
                .header("Cache-Control", "no-cache")
                .header("Connection", "keep-alive")
                .header("Content-Type", "application/json")
                .header("Origin", "https://www.lingluke.cn")
                .header("Pragma", "no-cache")
                .header("Referer", "https://www.lingluke.cn/frt/order")
                .header("Sec-Fetch-Dest", "empty")
                .header("Sec-Fetch-Mode", "cors")
                .header("Sec-Fetch-Site", "same-origin")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36")
                .header("apiversion", "1.5.0.1")
                .header("sec-ch-ua", "\"Chromium\";v=\"130\", \"Google Chrome\";v=\"130\", \"Not?A_Brand\";v=\"99\"")
                .header("sec-ch-ua-mobile", "?0")
                .header("sec-ch-ua-platform", "\"Windows\"")
                .build();

        try (Response response = client.newCall(request).execute()) {
            
            //根据结果判断是不是网货的单
            String result = response.body().string();

            JSONObject jsonObject = JSONObject.parseObject(result);
            HashMap<String, Object> data = (HashMap<String, Object>) jsonObject.get("data");
            List<Object> rows = (List<Object>) data.get("rows");
            JSONObject frtOrder = (JSONObject) rows.get(0);
            String frtId = frtOrder.getString("id");
            //司机名字
            String carrierName=frtOrder.getString("carrierName");
            //运单号
            String billFormId=frtOrder.getString("formId");
            map.put("frtId",frtId);
            map.put("billFormId",billFormId);
            map.put("carrierName",carrierName);
            return map;
        }catch (Exception e){
            logger.info("查询全部运单异常:"+e);
        }
        return null;
    }

    //运单提交
    //网货平台的邀约
    public static String pushWayBill(String formId){

        String requestBody = "{\"orderIds\":[\""+formId+"\"]}";

        Request request = new Request.Builder()
                .url("https://www.lingluke.cn/api/frt/order/zlAuthTiShen")
                .post(RequestBody.create(MediaType.parse("application/json"), requestBody)) // 需要指定媒体类型和请求体
                .header("Accept", "application/json")
                .header("Accept-Language", "zh-CN,zh;q=0.9")
                .header("Authorization", "Bearer "+LLK_TOKEN)
                .header("Cache-Control", "no-cache")
                .header("Connection", "keep-alive")
                .header("Content-Type", "application/json")
                .header("Origin", "https://www.lingluke.cn")
                .header("Pragma", "no-cache")
                .header("Referer", "https://www.lingluke.cn/whPlatForm/zlauthclientlist")
                .header("Sec-Fetch-Dest", "empty")
                .header("Sec-Fetch-Mode", "cors")
                .header("Sec-Fetch-Site", "same-origin")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36")
                .header("apiversion", "1.5.0.1")
                .header("sec-ch-ua", "\"Chromium\";v=\"130\", \"Google Chrome\";v=\"130\", \"Not?A_Brand\";v=\"99\"")
                .header("sec-ch-ua-mobile", "?0")
                .header("sec-ch-ua-platform", "\"Windows\"")
                .build();

        try (Response response = client.newCall(request).execute()) {
            String result = response.body().string();
            JSONObject jsonObject = JSONObject.parseObject(result);
            Integer code=jsonObject.getInteger("code");
            String message=jsonObject.getString("message");
            if(code == 200 && message.equals("请求成功")){
                return "推送成功";
            }else {
                return "推送失败"+jsonObject;
            }
        }catch (Exception e){
            logger.info("推送运单进行认证提审异常"+e);
            return "";
        }
    }
}
